import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, message, Modal, Select, Tree, TreeSelect, DatePicker, Checkbox, Tabs, InputNumber } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, getYear, getPayCycleDom, getNameByState, getStringByType, confirmDelete } from 'lib/fun'
import AreaInput from 'components/areaInput'
import FilterModule from './filterAuditoring'
import EditSuccessCitizen from './editSuccessCitizen'

const TreeNode = Tree.TreeNode;
const Option = Select.Option;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      projectCate: [],
      selectedRowKeys: [],
      data: [],
      visible: false,
      rowdata: {}
    }
    this.current = 1;   //当前第几页
    this.total = 10;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};

    this.isEdit = false;
  }

  componentDidMount(){
    const { config, addConfig } = this.props;
    if(!config.genderCode){
      // 性别
      addConfig('genderCode', 7);
    }
    if(!config.bankCode){
      // 所属银行
      addConfig('bankCode', 31);
    }
    this.loadData();
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
      this.setState({
        selectedRowKeys: []
      });

      this.current = 1;   //当前第几页
      this.total = 10;   //总共多少页
      this.pageSize = 10;   //每页多少行
      this.search = {};
      
      this.isEdit = false;
    }else if(!this.props.visible){
      this.loadData(nextProps);
    }
    // }else if(nextProps.batchId&&(nextProps.batchId != this.props.batchId||nextProps.type != this.props.type||!this.props.batchId)){
    //   this.loadData(nextProps);
    // }
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadData = (props) => {
    var self = this;
    self.setState({
      loading: true
    });
    const { identNumber, name, state } = this.search;
    const { type, batchId } = props?props:this.props;

    var url = getStringByType('url', type);
    if(url){
      Ajax({
        url: url,
        data: {
          identNumber,
          name,
          state: !state||_.isArray(state)&&state.length==0?[50]:state,
          batchId: batchId,
          currentPage: self.current,  //请求页码
          perPage: self.pageSize,   //每页数量
        },
        success: function(data){
          self.total = data.totalCount;
          self.setState({
            loading: false,
            data: data.list
          });
        },
        error: function(error){
          self.setState({
            loading: false
          });
          message.error(error);
        }
      });
    }
  }

  handleFilter = (option)=>{
    if(!_.isEqual(option, this.search)){
      this.search = option;
      this.loadData();
    }
  }

  renderContent = ()=>{
    return <Input id="desc" type="textarea"/>
  }

  operate = (option) => {
    var self = this;
    var fun = (desc)=>{
      self.setState({
        loading: true
      });
      Ajax({
        url: '/projectRegister/orgAuditorApprovalForRegister',
        data: {
          batchId: self.props.batchId,
          all: option.all?true:false,
          auditorType: option.type,
          reason: desc,
          registerIds: option.registerIds
        },
        success: function(data){
          self.setState({
            loading: false,
            selectedRowKeys: []
          });
          self.loadData();
          self.isEdit = true
        },
        error: function(error){
          self.setState({
            loading: false
          });
          message.error(error);
        }
      });
    }
    if(option.type == 2){
      Modal.confirm({
        title: '确定审核拒绝请填写理由',
        content: self.renderContent(),
        onOk() {
          return new Promise((resolve, reject) => {
            var desc = document.getElementById('desc').value;
            fun(desc);
            resolve();
          }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {},
      });
    }else{
      fun()
    }
  }

  doEdit = (row)=>{
    this.setState({
      visible: true,
      rowdata: row
    });
  }

  editOk = (rowdata)=>{
    var self = this;
    var find = _.find(self.state.data, (item)=>{
      return item.registerId == rowdata.registerId
    })
    Object.assign(find, rowdata);
    self.setState({
      visible: false,
      data: self.state.data
    });
    this.isEdit = true
  }

  editCancel = ()=>{
    this.setState({
      visible: false
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onClose(this.isEdit);
  }

  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/projectRegister/deleteCitizen',
        data: {
          "registerIds": [id]
        },
        success: function(data){
          // _.remove(self.state.data, function(d) {
          //   return d.registerId == id
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
          self.isEdit = true;
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除');
    });
  }

  renderPeople = ()=>{
    var self = this;
    const { getFieldDecorator } = this.props.form;
    const { visible, type } = this.props;
    const { bankCode } = this.props.config;

    const { config, common, see } = this.props;
    const columns = [{
      title: '用户姓名',
      dataIndex: 'name'
    }, {
      title: '证件号码',
      dataIndex: 'identNumber'
    }, {
      title: '性别',
      dataIndex: 'genderCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'genderCode', text) }</span>)
    }, {
      title: '开户银行',
      dataIndex: 'bankCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'bankCode', text) }</span>)
    }, {
      title: '银行卡号',
      dataIndex: 'bankNumber'
    }, {
      title: '用户归属区划',
      dataIndex: 'areaName'
    }, {
      title: '状态',
      dataIndex: 'state',
      render: (text, record) => (<span>{ getNameByState(common, "projectRegisterEn", text) }</span>)
    }, {
      title: '成功金额',
      dataIndex: 'subsidyMoney'
    }, {
      title: '失败原因',
      dataIndex: 'failReason'
    }];

    if(!see){
      columns.push({
        title: '操作',
        key: 'action',
        render: (text, record) => (<span><a onClick={this.doEdit.bind(this, record)} href="javascript:;">编辑</a> | <a onClick={this.doDelete.bind(this, record.registerId)} href="javascript:;">删除</a></span>)
      })
    }

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        self.setState({
          selectedRowKeys: selectedRowKeys
        });
      },
      selectedRowKeys: this.state.selectedRowKeys
    };

    return (
      <div>
        <FilterModule 
          handleFilter={ this.handleFilter }
          type="org"
          visible={visible}
        />
        <div style={{margin: '10px 0'}}>
          <Button 
            type="primary" 
            style={{marginRight: 10}} 
            onClick={ this.operate.bind(this, {
              all: false,
              type: 1,
              registerIds: this.state.selectedRowKeys
            }) }
            disabled={this.state.selectedRowKeys.length<=0}>
              审核通过
              {
                this.state.selectedRowKeys.length>0?(<span>({this.state.selectedRowKeys.length})</span>):""
              }
          </Button>
          <Button 
            type="primary"
            style={{marginRight: 10}}  
            onClick={ this.operate.bind(this, {
              all: false,
              type: 2,
              registerIds: this.state.selectedRowKeys
            }) }
            disabled={this.state.selectedRowKeys.length<=0}>
              审核拒绝
              {
                this.state.selectedRowKeys.length>0?(<span>({this.state.selectedRowKeys.length})</span>):""
              }
          </Button>
          <Button 
            type="primary"
            style={{marginRight: 10}}
            onClick={ this.operate.bind(this, {
              all: true,
              type: 1
            }) }
          >
            全部审核通过
          </Button>
          <Button 
            type="primary"
            onClick={ this.operate.bind(this, {
              all: true,
              type: 2
            }) }
          >
            全部审核拒绝
          </Button>
        </div>
        <Table 
          columns={columns}
          dataSource={ this.state.data }
          rowKey="registerId"
          pagination={ pagination }
          rowSelection={ rowSelection }
        />
        <EditSuccessCitizen
          visible={this.state.visible}
          rowdata={this.state.rowdata}
          onCancel={()=>{
            this.setState({
              visible: false
            });
          }}
          onSuccess={this.editOk}
          see={false}
        />
      </div>
    )
  }

  render() {
    const { visible, type } = this.props;
    
    return (
            <Modal 
              title={getStringByType('title', type)}
              visible={visible}
              onOk={ this.onCancel } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
              width="1100px"
            >
              { this.renderPeople() }
            </Modal>
            );
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(Form.create()(ModuleName))
